package com.yungu.swift.api.wxapi;

import com.yungu.swift.api.wxapi.pojo.SNSUserInfo;
import com.yungu.swift.api.wxapi.pojo.WeixinOauth2Token;
import com.yungu.swift.api.wxapi.util.AdvancedUtil;
import com.yungu.swift.assets.passenger.model.dto.PassengerDto;
import com.yungu.swift.assets.passenger.service.PassengerService;
import com.yungu.swift.utils.JsonUtils;
import com.yungu.swift.utils.MapUtils;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.jar.JarEntry;

/**
 * Created by cuixiuyin on 2018/5/3.
 */
@Slf4j
@Controller
@RequestMapping("/wx")
public class AuthController {

    @Reference
    private PassengerService passengerService;

    private static final String AUTHDENY = "authdeny";

    @RequestMapping("/test")
    public String test(HttpServletRequest request) {
        request.setAttribute("appid", WxConstants.APPID);
        return "wxPage/index";
    }

    /**
     * 生成用于获取access_token的Code的Url
     *
     * @return
     */
    @RequestMapping("/auth")
    public String wxAuth() {
        String url = getRequestCodeUrl(WxConstants.redirectUrl);
        return "redirect:" + url;
    }

    /**
     * 生成用于获取access_token的Code的Url
     *
     * @param redirectUrl
     * @return
     */
    public String getRequestCodeUrl(String redirectUrl) {
        return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                WxConstants.WXAPPID, redirectUrl, "snsapi_userinfo", "xxxx_state");
    }

    /**
     * 微信菜单的调用地址，获取授权信息并且返回跳转给前台
     *
     * @param request
     * @return
     */
    @RequestMapping("/getUserInfoAndRedirct")
    public String getUserInfoAndRedirct(HttpServletRequest request) {
        log.info("---------------------进入getUserInfoAndRedirct----------------------");
        // 用户同意授权后，能获取到code
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        log.info("---------------------code:" + code + "|state:" + state + "----------------------");
        // 用户同意授权
        if (!AUTHDENY.equals(code)) {
            // 获取网页授权access_token
            log.info("appid:{},secret:{},code:{}",WxConstants.WX_PUBLIC_APPID,WxConstants.WX_PUBLIC_APPSECRET,code);
            WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(WxConstants.WX_PUBLIC_APPID, WxConstants.WX_PUBLIC_APPSECRET, code);
            log.info("---------------------获取weixinOauth2Token----------------------{}", JsonUtils.toJSONString(weixinOauth2Token));
            int errorCode = 40163;
            if (weixinOauth2Token.getErrorCode() != null && weixinOauth2Token.getErrorCode() == errorCode) {
                //微信不允许5分钟之内相同Code重新请求，所以遇到这个错误我们就重新请求授权
                String url = getRequestCodeUrl(WxConstants.redirectUrl);
                return "redirect:" + url;
            }
            // 网页授权接口访问凭证
            String accessToken = weixinOauth2Token.getAccessToken();
            log.info("---------------------获取accessToken" + accessToken + "----------------------");
            // 用户标识
            String openId = weixinOauth2Token.getOpenId();
            log.info("---------------------获取openId" + openId + "----------------------");
            // 获取用户信息
            SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openId);
            log.info("---------------------获取snsUserInfo" + snsUserInfo + "----------------------");

            Map<String, Object> params = MapUtils.build(2);
            params.put("openId", openId);
            PassengerDto passengerDto = passengerService.get(params).getData();
            if (null != passengerDto) {
                snsUserInfo.setHeadImgUrl(passengerDto.getFace());
            }

            // 设置要传递的参数
            request.getSession().setAttribute("snsUserInfo", snsUserInfo);
            request.getSession().setAttribute("state", state);
            request.getSession().setAttribute("appid", WxConstants.WX_PUBLIC_APPID);
            log.info(request.getSession().getAttribute("snsUserInfo") + "");
        }
        //跳转到主页
        return "wxPage/index";
    }


}
